package com.foreknow.reflection;

import java.awt.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author shkstart
 * @create 2021-08-24 16:09
 */
public class ReflectionDemo {
    public void getNameTest() {
        String name = "tom123";
        Class cls = name.getClass();
        System.out.println("String类的名称是" + cls.getName());
        Button button = new Button();
        Class btnClass = button.getClass();
        System.out.println("Button类的名称" + btnClass.getName());
        Class superclass = btnClass.getSuperclass();
        System.out.println("Button类的父类的名称" + superclass);
    }

    public String testMethod(String str, Map hashMap) {
        String returnStr = "这是当前方法返回的字符串";
        System.out.println("获取到Map中的数据" + hashMap.get("name"));

        return returnStr;
    }

    //通过反射动态调用testMethod(String str,Map hashMap)方法
    public void getMethodTest() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {


        //1.获取到当前的类的对象
        Class cls = Class.forName("com.foreknow.reflection.ReflectionDemo");

        //两个参数  1.name  要获取的方法的名称   2.parameterTypes 方法参数的类型
        Class[] ptypes = new Class[2];
        ptypes[0] = Class.forName("java.lang.String");
        ptypes[1] = Class.forName("java.util.Map");
        //2.获取到当前要调用类对象方法的名称
        //两个参数  1.name  要获取的方法的名称   2.parameterTypes 方法参数的类型
        Method method = cls.getMethod("testMethod", ptypes);
        Object[] args = new Object[2];
        args[0] = "abc";
        HashMap hashMap = new HashMap();
        hashMap.put("name", "fender...");
        args[1] = hashMap;
        //3.调用testmethod方法
       String str=(String)method.invoke(new ReflectionDemo(), args);
        System.out.println(str);


    }


    public static void main(String[] args) {
        ReflectionDemo rd = new ReflectionDemo();
        rd.getNameTest();
        Map map = new HashMap<>();
        map.put("name", "123");
        rd.testMethod("abc", map);
        try {
            rd.getMethodTest();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
